import { globalModal } from "@/data";
import routeMap from "@/router/config/routeMap";
import { curWeek, uuid } from "@/utils";
import { Modal } from "antd";
import { makeAutoObservable, toJS } from "mobx"

class MobxStore {
    // 存放用户信息数据
    userInfo = {
        userCode: null,
        userName: null
    };
    //路由信息
    routes = routeMap;
    //角色列表
    allRoles = sessionStorage.getItem("allRoles") ? JSON.parse(sessionStorage.getItem("allRoles")) : []; //allRoles list
    //tabs config
    tabs = sessionStorage.getItem("tabs") ? JSON.parse(sessionStorage.getItem("tabs")) : []; //save tabs
    activeTabKey = sessionStorage.getItem("activeTabKey") ? JSON.parse(sessionStorage.getItem("activeTabKey")) : null; //激活的tab
    permissionList = sessionStorage.getItem("permissionList") ? JSON.parse(sessionStorage.getItem("permissionList")) : [];
    //字典json
    dictDataJson = sessionStorage.getItem("dictDataJson") ? JSON.parse(sessionStorage.getItem("dictDataJson")) : {};
    // 实现响应式
    constructor() {
        makeAutoObservable(this)
    }

    // 更新用户信息
    updateUserInfo = (params) => {
        this.userInfo = {
            ...params
        }
    }

    updateAllRoles = (list) => {
        this.allRoles = list;
        sessionStorage.setItem("allRoles", JSON.stringify(list));
    }

    updateRoutes = (routes) => {
        this.routes = routes;
    }
    updatePermissionList = (list) => {
        this.permissionList = list;
        sessionStorage.setItem("permissionList", JSON.stringify(list));
    }

    /**@description 判断是否是最后一个，控制是否允许关闭 */
    judegItems = (list) => {
        let items = [];
        if (list.length && list.length >= 1) {
            items = list.map(item => ({
                ...item,
                closable: list.length === 1 ? false : true
            }))
        }
        mobxState.setTabs(items)
    }

    /**@description 设置tabs */
    setTabs = (tabs = []) => {
        this.tabs = tabs;
        sessionStorage.setItem("tabs", JSON.stringify(tabs));
    }

    /**
   * 通用深度遍历查找器
   * @param {Array} nodes 节点数组 
   * @param {Function} predicate 匹配条件函数
   * @param {string} childKey 子节点属性名
   * @returns {any} 匹配节点的指定属性值
   */
    deepFind(nodes, predicate, childKey = 'children') {
        if (!Array.isArray(nodes)) return undefined;

        for (const node of nodes) {
            if (predicate(node)) return node;

            if (node[childKey]?.length) {
                const found = this.deepFind(node[childKey], predicate, childKey);
                if (found) return found;
            }
        }
        return undefined;
    }

    /**@description  查找是否需要询问 */
    findAskBeforeClose(routes, targetId) {
        const node = this.deepFind(
            routes,
            (n) => n.id === targetId
        );
        return node?.askBeforeClose || false;
    }


    /**@description 设置当前激活的tabs
     * @param {String} activeTabKey 当前激活的tabs key
     * @param {Array} newPanes 新的tabs
     * @param {Boolean} askBeforeClose 是否需要询问
     * @param {Boolean} isClose 是否关闭
     * @param {Boolean} isRefresh 是否刷新
     * 
     */

    setActiveTab = (key) => {
        sessionStorage.setItem("activeTabKey", JSON.stringify(key));
        this.activeTabKey = key;
    }

    addTabs = ({ label = String, key = uuid(), path = String, state = Object }) => {
        const newPanes = [...this.tabs];
        newPanes.push({
            label: label,
            key,
            path,
            state,
        });
        this.setTabs(newPanes);

    }
    onChangeTab = ({ key = String | Number, label = String, path = String, state = Object }) => {
        const item = this.tabs.filter(i => i.key === key);
        //如果存在，则直接切换激活key
        if (item.length && item.length > 0) {

            if (state === item.state) {
  
            } else {
                // 如果参数变化了，则更新参数
                let newPanes = [...this.tabs];
                newPanes = newPanes.map(tab => {
                    if (tab.key === key) {
                        return {
                            ...tab,
                            state: state
                        }
                    } else {
                        return tab;
                    }
                })

            }
        } else {
            this.addTabs({
                key, label, path, state
            })
        }
    }
    //关闭tab，传入一个tab的key，关闭这个tab页面，并且跳转到上一个tab页面
    closeTab = (key) => {
        const newPanes = [...this.tabs];
        const index = newPanes.findIndex(item => item.key === key);
        if (index > -1) {
            newPanes.splice(index, 1);

        }
    }

    //更新字典
    updateDictDataJson = (object) => {
        this.dictDataJson = JSON.stringify(object);
        sessionStorage.setItem("dictDataJson", JSON.stringify(object));

    }
}
// 实例化构建 并导出
const mobxState = new MobxStore();
export default mobxState;